package com.admin.system.service.impl;

import com.admin.model.dto.AuthUserDto;
import com.admin.system.security.jwt.JwtTokenUtils;
import com.admin.system.security.service.UserDetailsServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.AES;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author caixiaofeng
 * @version 1.0
 * @Description: <<>>
 * @company cxf
 * @create 2021-01-28 19:52
 */
@Service
public class AuthServiceImpl {
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private UserDetailsServiceImpl userDetailsService;
    @Resource
    private JwtTokenUtils jwtTokenUtils;

    public static void main(String[] args) {
        String randomKey = AES.generateRandomKey();
        System.out.println("randomKey = " + randomKey);


        String result = AES.encrypt("jdbc:mysql://127.0.0.1:3306/admin?characterEncoding=utf8&useSSL=true&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai", "19d774145302c48e");
        System.out.println("result = " + result);
    }

    /**
     * 登录认证换取jwt令牌
     *
     * @param authUserDto
     * @return
     */
    public String login(AuthUserDto authUserDto) throws RuntimeException {
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(authUserDto.getUsername(), authUserDto.getPassword());
        Authentication authenticate = authenticationManager.authenticate(upToken);
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        return jwtTokenUtils.generateToken((UserDetails)authenticate.getPrincipal());


    }

    public String login2(AuthUserDto authUserDto){
        UserDetails userDetails = userDetailsService.loadUserByUsername(authUserDto.getUsername());
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        return jwtTokenUtils.generateToken(userDetails);
    }


    /**
     * 刷新令牌
     *
     * @param oldToken
     * @return
     */
    public String refreshToken(String oldToken) {
        //返回最新的令牌
        String newToken = jwtTokenUtils.refreshToken(oldToken);
        Assert.notEmpty(newToken, "刷新令牌失败");
        return newToken;
    }

}
